package com.example.product.controller;



import com.example.common.result.PageBean;
import com.example.common.result.Result;
import com.example.model.product.pojo.Product;
import com.example.product.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
public class ProductController {
    @Autowired
    private ProductService productService;
    @Autowired
    private RedisTemplate redisTemplate;
    @GetMapping("/admin/products")
    public Result page(@RequestParam(value ="page",defaultValue ="1") Integer page, @RequestParam(value = "PageSize",defaultValue = "5") Integer PageSize, String name, String description){
        PageBean page1 = productService.page(page, PageSize, name, description);
        return Result.success(page1);
    }

    /**
     * 增加
     * @param product
     * @return
     */
    @PostMapping("/admin/products")
    public Result save(@RequestBody Product product){
        cleanCache();
        productService.save(product);
        return Result.success();
    }
    @GetMapping("/admin/products/{id}")
    public Result selectById(@PathVariable Integer id){
        Product product = productService.selectById(id);
        return Result.success(product);
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @DeleteMapping("/admin/products/{ids}")
    public Result deleteById(@PathVariable List<Integer> ids){
        cleanCache();
    productService.deleteById(ids);
    return Result.success();
    }

    /**
     * 更新
     * @param product
     * @return
     */
    @PutMapping("/admin/products")
    public Result update(@RequestBody Product product){
        cleanCache();
        productService.update(product);
        return Result.success();
    }


    private void cleanCache(){
        Set keys = redisTemplate.keys("good_*");
        redisTemplate.delete(keys);
    }

}
